#include "CmdFile.h"
#include <iostream>
#include <algorithm>
#include <ctime>
#include <fstream>

CmdFile::CmdFile(void)
{
	m_groupKeyDef.insert("FILENAME");
	m_groupKeyDef.insert("IMPOSX");
	m_groupKeyDef.insert("IMPOSY");
}

CmdFile::~CmdFile(void)
{
	m_groups.clear();
	m_randGroups.clear();
}

string retrieveSubKeyValue( const string& subkey, const string &line )
{
	if( subkey.size() >= line.size() ) return "";
	size_t bpos = line.find( subkey ) + subkey.length()+1;
	size_t epos = line.find(",", bpos);
	return line.substr( bpos, epos-bpos );
}

void CmdFile::addLine( const string& line )
{
	CmdGroupKey key;
	for( set<string>::iterator iter = m_groupKeyDef.begin(); iter != m_groupKeyDef.end(); iter++ )
	{
		key[*iter] = retrieveSubKeyValue( *iter, line );

		// need to retrieve the "base" of the filename
		if( (*iter).compare("FILENAME") == 0 )
		{
			size_t bpos = key[*iter].find_last_of("/\\") + 1;
			size_t epos = key[*iter].find_first_not_of("0123456789", bpos);
			key[*iter] = key[*iter].substr( bpos, epos-bpos-1);
		}

		if( key[*iter].empty() ) return;
		//cout << key[*iter] << ",";
	}
	//cout << endl;
	

	if( m_groups[ key ] == NULL ) {
		list<string> lines;
		m_randGroups.push_back( lines );
		m_groups[ key ] = &m_randGroups.back();
	}
	m_groups[ key ]->push_back( line );
}
void CmdFile::randomize()
{
	srand(time(0));
    random_shuffle(m_randGroups.begin(), m_randGroups.end());
}
void CmdFile::write( ofstream &out  ) const
{
	for( Groups::const_iterator giter = m_randGroups.begin(); giter != m_randGroups.end(); giter++ )
	{
		for( Group::const_iterator liter = (*giter).begin(); liter != (*giter).end(); liter++ )
		{
			out << *liter << endl;
		}
	}
}